import React, { useEffect, useRef, forwardRef, useImperativeHandle } from 'react';
import type { ECharts, EChartsOption, SetOptionOpts } from 'echarts';
import { init } from 'echarts';
import type { ForwardedRef } from 'react';

export interface BaseChartProps {
  option: EChartsOption;
  style?: React.CSSProperties;
  settings?: SetOptionOpts;
  loading?: boolean;
  theme?: 'light' | 'dark' | string;
  onChartReady?: (chart: ECharts) => void;
}

const BaseChart = forwardRef<ECharts | undefined, BaseChartProps>(
  (
    { option, style, settings, loading, theme = 'light', onChartReady },
    ref: ForwardedRef<ECharts | undefined>
  ) => {
    const chartRef = useRef<HTMLDivElement>(null);
    const chartInstance = useRef<ECharts | null>(null);

    // 初始化图表
    useEffect(() => {
      if (chartRef.current) {
        chartInstance.current = init(chartRef.current, theme);
        onChartReady?.(chartInstance.current);
      }

      return () => {
        chartInstance.current?.dispose();
      };
    }, [theme]);

    // 更新配置
    useEffect(() => {
      if (chartInstance.current) {
        chartInstance.current.setOption(option, settings);
      }
    }, [option, settings, theme]);

    // 处理加载状态
    useEffect(() => {
      if (chartInstance.current) {
        loading
          ? chartInstance.current.showLoading()
          : chartInstance.current.hideLoading();
      }
    }, [loading]);

    // 暴露实例给父组件
    useImperativeHandle(ref, () => chartInstance.current as ECharts);

    return (
      <div
        ref={chartRef}
        style={{ width: '100%', height: '100%', ...style }}
      />
    );
  }
);

export default BaseChart;